package thread;
//实现一个定时器

/* abstract class MyTimerTask implements Runnable {
    @Override
    public abstract void run();
}*/
//给人看的叫格式化时间 给计算机看的叫 时间戳

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable task;
    //记录任务执行的时刻
    private long time;
    public MyTimerTask(Runnable task,long time){
        this.task=task;
        this.time=time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }
    public void run(){
        task.run();
    }
    public long getTime(){
        return time;
    }
}
class MyTimer{
    private PriorityQueue<MyTimerTask> queue=new PriorityQueue<>();
    private Object blocker=new Object();

    public void schedule(Runnable task,long delay){
        //System.currentTimeMillis() 指当前时刻的时间戳 返回一个long类型 毫秒级的时间戳
        synchronized (blocker){
            MyTimerTask timerTask=new MyTimerTask(task,System.currentTimeMillis()+delay);
            queue.offer(timerTask);
            blocker.notify();
        }
    }

    public MyTimer(){
        Thread t=new Thread(()->{
           while(true){
               synchronized (blocker){
                   try {
                       while(queue.isEmpty()){
                           blocker.wait();
                       }
                       MyTimerTask task= queue.peek();//取队头元素
                       long curtime= System.currentTimeMillis();
                       if(curtime<task.getTime()){
                           blocker.wait(task.getTime()-curtime);
                       }else{
                           queue.poll();//移除队头元素
                           task.run();
                       }
                   }catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
           }
        });
        t.start();
    }

}
public class Demo34 {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        ScheduledExecutorService scheduledExecutorService =Executors.newScheduledThreadPool(4);//标准库提供了带有定时器的线程池
        //scheduledExecutorService.schedule();
    }
}
